from flask import g
from flask import request, jsonify
from info import constants
from info.models import News, Category
from . import index_blu
from flask import render_template, current_app
from info.utils.common import user_login_data
from info.utils.response_code import RET


# 新闻列表页
@index_blu.route('/news_list')
def get_news_list():
    # 获取参数
    cid = request.args.get('cid', '1')
    page = request.args.get('page','1')
    per_page = request.args.get('per_page','10')

    # 校验参数,因为参数是数字类型的 用int强制转换类型,可以确定参数是否是int类型
    try:
        cid = int(cid)
        page = int(page)
        per_page = int(per_page)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR,errmsg='参数错误')
    # 查询数据库
    filter = []
    if cid !=1:
        filter.append(News.category_id == cid)
        # *filter 就是把查询条件的列表展开
    try:
        paginate = News.query.filter(*filter).order_by(News.create_time.desc()).paginate(page, per_page, False)
    except Exception as e:
       current_app.logger.error(e)
       return jsonify(errno=RET.DBERR,errmsg='数据库查询错误')
    # 获取查询结果
    news_model_list = paginate.items
    # 获取总分页
    total_page = paginate.pages
    # 获取当前分页
    current_page = paginate.page

    news_dict_li = []
    for news in news_model_list:
        news_dict_li.append(news.to_basic_dict())
    data = {
        "news_dict_li":news_dict_li,
        "total_page":total_page,
        "current_page":current_page
    }
    return jsonify(errno=RET.OK,errmsg='成功',data=data)

# 首页接口
# 使用蓝图路由  然后去创建APP的地方注册蓝图对象
@index_blu.route('/')
@user_login_data
def index():
    # 1. 登陆数据
    user = g.user
    # 2. 排行数据
    # 查询数据库操作
    news_list = []
    try:
        news_list = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)
    except Exception as e:
        # 记录错误日志
        current_app.logger.error(e)
    news_dict_li = []
    for news in news_list:
        news_dict_li.append(news.to_review_dict())

    # 3. 分类数据(查询数据库,传入模板渲染)
    # 查询数据库 如果查询数据库失败就是用这个空列表
    categories = []
    try:
        categories = Category.query.all()
    except Exception as e:
        current_app.looger.error(e)

    category_li = []
    for category in categories:
        category_li.append(category.to_dict())

    # 返回user数据,将模型数据转字典
    data = {
        'user':user.to_dict() if user else None,
        'news_dict_li':news_dict_li,
        'category_li':category_li
    }
    return render_template('news/index.html',data=data)

# 返回网页图标
@index_blu.route('/favicon.ico')
def favicon():
    return current_app.send_static_file('news/favicon.ico')
